package com.xzq.socket.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @Author xzq
 * @Description //适配器
 * @Date 2021/11/17 16:22
 * @Version 1.0.0
 **/
public abstract class ChannelAdapter extends Thread {
    private Socket socket;
    private ChannelHandler channelHandler;
    private Charset charset;

    public ChannelAdapter(Socket socket, Charset charset) {
        this.socket = socket;
        this.charset = charset;
        while (!socket.isConnected()) {
            break;
        }
        channelHandler=new ChannelHandler(socket, charset);
        channelActive(channelHandler);
    }

    @Override
    public void run() {
        try {
            InputStream is = this.socket.getInputStream();
            int len;
            byte[] buffer = new byte[1024];
            while (true) {
                if ((len = is.read(buffer)) != -1) {
                    channelRead(channelHandler, new String(buffer, 0, len, charset));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //链接通知抽象类
    public abstract void channelActive(ChannelHandler channelHandler);

    //读取消息抽象类
    public abstract void channelRead(ChannelHandler ctx, Object msg);
}
